<template>
  <el-dialog
    v-model="visible"
    title="发送图片"
    width="500px"
    :before-close="handleClose"
    class="image-upload-dialog"
  >
    <div class="upload-container">
      <el-upload
        ref="imageUploadRef"
        drag
        multiple
        :show-file-list="false"
        action=""
        :limit="10"
        accept="image/*"
        :before-upload="handleImageBeforeUpload"
        :on-exceed="handleExceed"
      >
        <div class="upload-area">
          <el-icon class="upload-icon"><Picture /></el-icon>
          <div class="upload-text">点击或拖拽图片到此处上传</div>
          <div class="upload-hint">支持 JPG、PNG、GIF 格式，单个文件不超过 10MB</div>
        </div>
      </el-upload>
    </div>

    <!-- 上传进度 -->
    <div v-if="isUploading" class="flex items-center space-x-2">
        <el-progress :percentage="100" :show-text="false" />
        <span class="text-sm text-gray-600">上传中...</span>
    </div>

    <!-- 已上传图片预览 -->
    <div v-if="uploadedImages.length > 0" class="uploaded-images-section">
        <div class="section-title">
        已选择的图片 ({{ uploadedImages.length }})
        </div>
        <div class="images-grid">
            <div
                v-for="(image, index) in uploadedImages"
                :key="index"
                class="image-item"
            >
                <img
                :src="image.url"
                :alt="image.name"
                class="image-preview"
                >
                <div class="image-overlay">
                <el-button
                    type="danger"
                    size="small"
                    circle
                    @click="removeUploadedImage(index)"
                    class="delete-btn"
                >
                    <el-icon><Delete /></el-icon>
                </el-button>
                </div>
            </div>
        </div>
    </div>


    <template #footer>
        <div class="footer-wrap">
            <div class="text-sm text-gray-500">
            {{ uploadedImages.length }}/10 张图片
            </div>
            <div class="space-x-2">
            <el-button @click="visible = false">
                取消
            </el-button>
            <el-button
                type="primary"
                :disabled="uploadedImages.length === 0 || isUploading"
                @click="sendImageMessages"
            >
                发送 {{ uploadedImages.length > 0 ? `(${uploadedImages.length})` : '' }}
            </el-button>
            </div>
        </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineExpose, nextTick, defineEmits} from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Delete } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles } from 'element-plus'
import { useIMStore } from '/@/stores/im'
import { truncate } from 'node:fs/promises'
import COS from 'cos-js-sdk-v5'
import dayjs from 'dayjs'
import api from "/@/api/common";

// 定义 emits
const emit = defineEmits(['send-images'])
const cosObj = new COS({
  Protocol: 'https:', // 使用 https 协议
  async getAuthorization(options: any, callback) {
    const { data } = await api.getCredential()
    console.log(options)
    callback({
      TmpSecretId: data.tmpSecretId,
      TmpSecretKey: data.tmpSecretKey,
      SecurityToken: data.sessionToken,
      // 建议返回服务器时间作为签名的开始时间，避免客户端本地时间偏差过大导致签名错误
      StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
      ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000000
      ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
    })
  },
})

const imStore = useIMStore()
// 响应式数据
const isUploading = ref(false)
const uploadedImages = ref<any[]>([])
const visible = ref(false)
const fileList = ref<UploadFile[]>([])
const uploadRef = ref()


/**
 * 上传超出10张图片时的处理
 */
const handleExceed = () => {
    return ElMessage.error('已达到最大上传数量(10张)，请先删除一些图片')
}


// 移除已上传的图片
function removeUploadedImage(index: number) {
  uploadedImages.value.splice(index, 1)
}

// 发送图片消息
async function sendImageMessages() {
  if (uploadedImages.value.length === 0) {
    ElMessage.warning('请先上传图片')
    return
  }

  if (!imStore.currentConversation) {
    ElMessage.warning('请先选择聊天对象')
    return
  }

  const to = imStore.currentConversation?.userProfile?.userID
  if (!to) {
    ElMessage.warning('无法获取聊天对象信息')
    return
  }

  let successCount = 0
  let failCount = 0

  // 发送每张图片
  for (const [index, image] of uploadedImages.value.entries()) {
    try {
      const result = await imStore.sendImageCustomMessage(image.url, image.name, to, 'C2C')
      if (result && result.code === 0) {
        successCount++
      }
      else {
        failCount++
        console.error(`图片 ${index + 1} 发送失败:`, result)
      }
    }
    catch (error) {
      failCount++
      console.error(`图片 ${index + 1} 发送异常:`, error)
    }
  }

  if (successCount > 0) {
    ElMessage.success(`成功发送 ${successCount} 张图片`)
  }
  if (failCount > 0) {
    ElMessage.error(`发送失败 ${failCount} 张图片`)
  }

  visible.value = false
  uploadedImages.value = []
  nextTick(() => {
    // scrollToBottom()
    emit('send-images', true)
  })
}
// 处理图片上传前的验证
async function handleImageBeforeUpload(file: File) {
  // 检查图片数量限制（包括正在上传的）
  const currentCount = uploadedImages.value.length
  console.log(currentCount)

  if (currentCount >= 10) {
    ElMessage.error('最多只能上传10张图片!')
    return false
  }

  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }

  // 先添加一个占位项，防止并发上传时数量检查失效
  const placeholderItem = {
    uid: file.name + Date.now(),
    url: '',
    name: file.name,
    file,
    loading: true,
  }
  uploadedImages.value.push(placeholderItem)

  isUploading.value = true
  try {
    const fileName = `/uploads/images/${dayjs().format('YYYYMMDD')}/${new Date().getTime()}_${file.name}`
    const result = await cosObj.uploadFile({
      Bucket: 'yj-mail-1307961934',
      Region: 'ap-shanghai',
      Key: fileName,
      Body: file,
    })

    if (result.statusCode === 200) {
      const imageUrl = `https://${result.Location}`
      // 更新占位项
      const index = uploadedImages.value.findIndex(item => item.uid === placeholderItem.uid)
      if (index !== -1) {
        uploadedImages.value[index] = {
          url: imageUrl,
          name: file.name,
          file,
          uid: placeholderItem.uid,
        }
      }
      ElMessage.success('图片上传成功')
    }
    else {
      // 上传失败，移除占位项
      const index = uploadedImages.value.findIndex(item => item.uid === placeholderItem.uid)
      if (index !== -1) {
        uploadedImages.value.splice(index, 1)
      }
    }
  }
  catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
    // 上传失败，移除占位项
    const index = uploadedImages.value.findIndex((item:any) => item.uid === placeholderItem.uid)
    if (index !== -1) {
      uploadedImages.value.splice(index, 1)
    }
  }
  finally {
    isUploading.value = false
  }

  return false // 阻止 el-upload 的默认上传行为
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
}

const open = (list:any[]) => {
    if(list && list.length > 0) {
        uploadedImages.value = list
    }
    visible.value = true
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.footer-wrap {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
/* 图片网格布局样式 */
.uploaded-images-section {
    margin-top: 16px;
    margin-bottom: 16px;
}

.section-title {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
    margin-bottom: 12px;
}

.images-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
}

.image-item {
    position: relative;
    width: 100%;
    height: 100px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    background-color: #f5f7fa;
}

.image-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.2s ease;
    border-radius: 8px;
}

.image-item:hover .image-overlay {
    opacity: 1;
}

.delete-btn {
    background-color: #f56c6c !important;
    border-color: #f56c6c !important;
    color: white !important;
}

.delete-btn:hover {
    background-color: #f78989 !important;
    border-color: #f78989 !important;
}
</style>
